package com.iotimc.attendancesystem.attendance;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.smdt.SmdtManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextClock;
import android.widget.TextView;

import com.iotimc.attendancesystem.App;
import com.iotimc.attendancesystem.Contract;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.base.BaseActivity;
import com.iotimc.attendancesystem.event.AttendanceEvent;
import com.iotimc.attendancesystem.event.NoticeEvent;
import com.iotimc.attendancesystem.event.TimePromptEvent;
import com.iotimc.attendancesystem.server.CoreService;
import com.iotimc.attendancesystem.server.ServerStatusReceiver;
import com.iotimc.attendancesystem.util.PictureManager;
import com.iotimc.attendancesystem.util.ShareUtil;
import com.iotimc.attendancesystem.util.TtsUtil;
import com.iotimc.attendancesystem.welcome.WelcomeContract;
import com.iotimc.attendancesystem.welcome.WelcomePresenter;
import com.iotimc.comass.util.IotimcSerialHelper;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.PfsBioInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by cwj on 2017/11/27.
 *
 * @author cwj
 */

public class SystemActivity extends BaseActivity implements WelcomeContract.View {
    private int time = 30;
    private final int defaultTime = 60;
    private static final String TAG = "SystemActivity";
    @BindView(R.id.iv_system_logo)
    ImageView mIvSystemLogo;
    @BindView(R.id.tv_system_tittle)
    TextView mTvSystemTittle;
    @BindView(R.id.iv_system_login)
    ImageView mIvSystemLogin;
    @BindView(R.id.iv_system_check)
    ImageView mIvSystemCheck;
    @BindView(R.id.tc_index_timeText)
    TextClock mTcIndexTimeText;
    @BindView(R.id.tc_index_yearText)
    TextClock mTcIndexYearText;
    @BindView(R.id.tc_index_weekText)
    TextClock mTcIndexWeekText;
    @BindView(R.id.system_face)
    LinearLayout mSystemFace;
    @BindView(R.id.system_fragment)
    FrameLayout mSystemFragment;
    @BindView(R.id.tv_system_status)
    TextView mTvSystemStatus;

    @BindView(R.id.ll_system_loading)
    LinearLayout mLlLoading;
    @BindView(R.id.iv_system_loading)
    ImageView mIvLoading;


    private Disposable mSubscribe;
    private PopupWindow window;
    WelcomeContract.Presenter presenter;
    private MainFragment mMainFragment;
    private FaceLoginFragment mLoginFragment;
    private LoginFragment mLoginFragment1;
    private AttendanceFragment2 mAttendanceFragment;
    private Intent mService;
    /**
     * Accept and server status.
     */
    private ServerStatusReceiver mReceiver;
    private Disposable mDisposable;


    @OnClick({R.id.iv_system_check, R.id.iv_system_check2})
    void checkFace() {
        startTime();
        time = defaultTime;
        switchContent(mAttendanceFragment);
    }

    @OnClick(R.id.ll_system_login)
    void showPop() {
        startTime();
        time = 15;
        showPopup(mIvSystemLogin);
    }


    @Override
    protected int getResId() {
        return R.layout.activity_system;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAttendanceFragment = new AttendanceFragment2();

        mMainFragment = new MainFragment();
        mLoginFragment = new FaceLoginFragment();

        mLoginFragment1 = new LoginFragment();
        currentFragment = mMainFragment;

        PictureManager.getInstance().load(SystemActivity.this, R.drawable.system_logo, mIvSystemLogo, true);
        PictureManager.getInstance().loadGif(SystemActivity.this, R.drawable.system_gif_loading, mIvLoading, 1);

        presenter = new WelcomePresenter(this, this);

        presenter.initDevice();

        Intent startIntent = new Intent(this, TimePromptService.class);
        startService(startIntent);
        //startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
        // AndServer run in the service.
        mService = new Intent(this, CoreService.class);
        mReceiver = new ServerStatusReceiver(this);
        mReceiver.register();
        startService(mService);
    }

    AttendanceContract.Presenter attendancePresenter;


    @Override
    protected void onResume() {
        super.onResume();
        //控制底部菜单栏是否显示
        SmdtManager.create(this).smdtSetStatusBar(this, false);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        stopTime();
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable = null;
        }
        super.onPause();
    }

    @Override
    public void showLoading() {
        mTvSystemStatus.setText(R.string.initing);
    }

    @Override
    public void showMessage(final int messageId) {
        Log.d(TAG, "showMessage: " + getString(messageId));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (R.string.initSuccuss == messageId) {
                    mTvSystemStatus.setText(messageId);
                    ShareUtil.saveBoolean(SystemActivity.this, true, Contract.DEVICE_STATUS);
                } else {
                    mTvSystemStatus.setText(messageId);
                    mTvSystemStatus.setTextColor(getResources().getColor(R.color.yellow));
                    ShareUtil.saveBoolean(SystemActivity.this, false, Contract.DEVICE_STATUS);
                    TtsUtil.ttsSpeek("设备初始化失败，5秒后重启系统！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent mStartActivity = new Intent(App.getInstance(), SystemActivity.class);
                            int mPendingIntentId = 123456;
                            PendingIntent mPendingIntent = PendingIntent.getActivity(App.getInstance(),
                                    mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                            AlarmManager mgr = (AlarmManager) App.getInstance().getSystemService(Context.ALARM_SERVICE);
                            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                            System.exit(0);
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    }, 5000);

                }
                attendancePresenter = new AttendancePresenter(null);
                mAttendanceFragment.setPresenter(attendancePresenter);
                mLoginFragment.setPresenter(attendancePresenter);

                init();
            }
        });


    }


    private void init() {
        mSystemFace.setVisibility(View.VISIBLE);
        switchContent(mMainFragment);
        mLlLoading.setVisibility(View.GONE);
    }

    private void showPopup(View view) {
        View popupView = LayoutInflater.from(this).inflate(R.layout.itemlist_popupwindow, null, false);
        popupView.findViewById(R.id.bt_itemlist_face).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchContent(mLoginFragment);
                if (window != null) {
                    window.dismiss();
                    time = defaultTime;
                }
            }
        });
        popupView.findViewById(R.id.bt_itemlist_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchContent(mLoginFragment1);
                if (window != null) {
                    window.dismiss();
                    time = defaultTime;
                }

            }
        });

        window = new PopupWindow(popupView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        window.setBackgroundDrawable(new ColorDrawable(0xee4220));
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        window.setAnimationStyle(R.style.popup_window_stting_anim);
        window.update();
        window.showAtLocation(view, Gravity.TOP | Gravity.END, 40, 100);
    }

    @Override
    protected void onDestroy() {
        presenter.close();
        IotimcSerialHelper.quit();
        stopService(mService);
        mReceiver.unRegister();
        Ast2600JNI.getInstance().pisFcInfraredLedControl(
                PfsBioInfo.getInstance().mContextID,
                PfsBioInfo.PFSBIO_IR_LED_OFF);
        Ast2600JNI.getInstance().pisLedControl(
                PfsBioInfo.getInstance().mContextID, PfsBioInfo.PFSBIO_OKNOLED,
                PfsBioInfo.PFSBIO_LED_OFF);
        super.onDestroy();
    }

    private void startTime() {
        stopTime();
        //time = defaultTime;
        mSubscribe = Observable
                .interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        time--;
                        Log.i(TAG, "accept: " + time);
                        if (time <= 0) {
                            switchContent(mMainFragment);

                            if (window != null) {
                                window.dismiss();
                            }

                            mSubscribe.dispose();
                            time = defaultTime;

                            //closeLed();
                        }
                    }
                });
    }


    private void closeLed() {
        Observable.timer(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (!mMainFragment.isHidden()) {
                            /**
                             *LED灯亮的控制
                             * @param contextID 设备ID
                             * @param ledKind 灯的类型  PFSBIO_OKNOLED PFSBIO_OKLED PFSBIO_NOLED等
                             * @param controlValue 开或者关 PFSBIO_LED_ON PFSBIO_LED_OFF
                             * @return int类型          PFSBIO_OK(0)成功，其他为失败
                             */
                            int i = Ast2600JNI.getInstance().pisLedControl(
                                    PfsBioInfo.getInstance().mContextID, PfsBioInfo.PFSBIO_OKNOLED,
                                    PfsBioInfo.PFSBIO_LED_OFF);
                            int i1 = Ast2600JNI.getInstance().pisLedControl(
                                    PfsBioInfo.getInstance().mContextID, PfsBioInfo.PFSBIO_OKLED,
                                    PfsBioInfo.PFSBIO_LED_OFF);
                            int i2 = Ast2600JNI.getInstance().pisLedControl(
                                    PfsBioInfo.getInstance().mContextID, PfsBioInfo.PFSBIO_NOLED,
                                    PfsBioInfo.PFSBIO_LED_OFF);
                            Log.i(TAG, "accept: " + i + "----------------" + i1 + "-------------" + i2);
                        }
                    }
                });
    }

    public void stopTime() {
        if (mSubscribe != null) {
            if (!mSubscribe.isDisposed()) {
                mSubscribe.dispose();
            }
            mSubscribe = null;
        }
    }

    public void showMainFragment() {
        switchContent(mMainFragment);
    }

    private Fragment currentFragment;

    public void switchContent(Fragment to) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if ((currentFragment instanceof FaceLoginFragment || currentFragment instanceof AttendanceFragment2)
                && !(to instanceof FaceLoginFragment) && !(to instanceof AttendanceFragment2)) {
            if (attendancePresenter != null) {
                Log.i(TAG, "attendancePresenter stop: " + attendancePresenter.isRuning());
                attendancePresenter.stopAttendance();
            }
        }

        if (!to.isAdded()) {
            if (currentFragment != to) {
                fragmentTransaction.hide(currentFragment);
            }
            fragmentTransaction.add(R.id.system_fragment, to).commit();
        } else {
            if (to == currentFragment) {
                return;
            }
            fragmentTransaction.hide(currentFragment).show(to).commit();
        }
        currentFragment = to;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        time = defaultTime;
        return super.onTouchEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onAttendanceEvent(AttendanceEvent event) {
        Log.i(TAG, "onAttendanceEvent: 收到消息了");
        boolean status = event.getStatus();
        if (status) {
            time = defaultTime;
        }
    }


    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onTimePromptEvent(TimePromptEvent event) {
        Log.i(TAG, "TimePromptEvent: 收到消息了");
        boolean status = event.getStatus();
        if (status) {
            if (mMainFragment.isAdded()) {
                mMainFragment.getTemp();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeEventEvent(NoticeEvent event) {
        Log.i(TAG, "NoticeEvent: 收到消息了");
        boolean status = event.getStatus();
        if (status) {
            if (mMainFragment.isAdded()) {
                mMainFragment.getNotice();
            }
        }
    }

    public void setTime(int time) {
        this.time = time;
    }
}
